﻿using Net.System;
using System.Net;
using System.Net.Sockets;

namespace SocketTest
{
    internal class Server
    {
        internal ListSafe<Socket> clients = new ListSafe<Socket>();
        internal Socket server;

        public void Start()
        {
            server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            server.NoDelay = true;
            server.Bind(new IPEndPoint(IPAddress.Any, 5000));
            server.Listen(50000);
            Accept();
            Console.WriteLine("服务器已启动，等待连接...");
        }

        private void Accept()
        {
            //for (int i = 0; i < 50000; i++)
            //{
            //    var e = new SocketAsyncEventArgs();
            //    e.SetBuffer(new byte[1024], 0, 1024);
            //    e.Completed += (s, e) =>
            //    {
            //        var client = e.AcceptSocket;
            //        clients.Add(client);
            //    };
            //    server.AcceptAsync(e);
            //}
            server.BeginAccept(callback =>
            {
                var client = server.EndAccept(callback);
                clients.Add(client);
                Accept();
            }, null);
        }
    }
}
